﻿using CIS.DB;
using CIS.Web.Models;
using CIS.Web.Properties;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using ThoughtWorks.QRCode.Codec;
using static CIS.Web.Common.ConstValues;

namespace CIS.Web.Common
{
	public static class Utility
	{
		public static bool HasSystemRole(ICISPrincipal principal, string functionId, RoleType role)
		{
			return principal.UserRoleActions.Any(x =>
					x.FunctionID == functionId &&
					(role == RoleType.浏览 ? x.Browse.Value == 1 : true) &&
					(role == RoleType.添加 ? x.Add.Value == 1 : true) &&
					(role == RoleType.修改 ? x.Modify.Value == 1 : true) &&
					(role == RoleType.删除 ? x.Delete.Value == 1 : true));
		}

		public static bool HasConferenceRole(ICISPrincipal principal, string conferenceID, string functionId, RoleType role)
		{
			return principal.ConferenceRoleActions.Any(x =>
					x.ConferenceID == conferenceID &&
					x.FunctionID == functionId &&
					(role == RoleType.浏览 ? x.Browse.Value == 1 : true) &&
					(role == RoleType.添加 ? x.Add.Value == 1 : true) &&
					(role == RoleType.修改 ? x.Modify.Value == 1 : true) &&
					(role == RoleType.删除 ? x.Delete.Value == 1 : true));
		}

		public static object CreateSuccessJsonResult(string message = "", object data = null)
		{
			return new { result = AjaxSuccessResult, message = message, data = data };
		}

		public static object CreateFailJsonResult(string message = "", object data = null)
		{
			return new { result = AjaxFailResult, message = message, data = data };
		}

		/// <summary>
		/// 写Log
		/// </summary>
		/// <param name="principal"></param>
		/// <param name="url"></param>
		/// <param name="controller"></param>
		/// <param name="actionName"></param>
		/// <param name="viewName"></param>
		/// <param name="conferenceId"></param>
		/// <param name="newsListId"></param>
		/// <param name="newsId"></param>
		public static void InsertLog(ICISPrincipal principal, string url, string controller, string actionName, string viewName = "",
				string conferenceId = "", string newsListId = "", string newsId = "")
		{
			string controllerName = controller.GetControllerName();
			string pageLogsType = string.Empty;

			if (PageLogsType_System.Contains(controllerName))
			{
				pageLogsType = PageLogsType.系统;
			}
			else if (PageLogsType_Conference.Contains(controllerName))
			{
				pageLogsType = PageLogsType.会议;
			}
			else
			{
				pageLogsType = PageLogsType.用户;
			}

			//匿名时获取登录者IP add by zhaoyueqi 2018-06-14
			//var userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
			var userHostAddress = GetRealIP();
			//log4net.ILog logger = log4net.LogManager.GetLogger("Test");
			//logger.Error(userHostAddress);

			var log = new LogInfo
			{
				ID = GetTableId(TableName.LogInfo),
				PageLogsType = pageLogsType,
				Action = actionName,
				ConferenceId = conferenceId,
				NewsListId = newsListId,
				NewsId = newsId,
				View = viewName,
				Controller = controllerName,
				Path = url.Replace(":8080", string.Empty),
				Client = 客户端.PC,
				Status = Status.正常,
				Sort = 6666,
				Remark = string.Empty,
				Creator = principal != null ? principal.UserName : string.Empty,
				CreateIP = principal != null ? principal.IP : userHostAddress,
				CreateDate = DateTime.Now,
				Updater = principal != null ? principal.UserName : string.Empty,
				UpdateIP = principal != null ? principal.IP : userHostAddress,
				UpdateDate = DateTime.Now
			};

			var dbContext = new CISEntities();
			dbContext.LogInfo.Add(log);
			dbContext.SaveChanges();
		}

		/// <summary>
		/// 分析 url 字符串中的参数信息
		/// </summary>
		/// <param name="url">输入的 URL</param>
		/// <param name="baseUrl">输出 URL 的基础部分</param>
		/// <param name="nvc">输出分析后得到的 (参数名,参数值) 的集合</param>
		public static void ParseUrl(string url, out string baseUrl, out NameValueCollection nvc)
		{
			if (url == null)
			{
				throw new ArgumentNullException("url");
			}
			nvc = new NameValueCollection();
			baseUrl = string.Empty;
			if (url == string.Empty)
			{
				return;
			}
			int questionMarkIndex = url.IndexOf('?');
			if (questionMarkIndex == -1)
			{
				baseUrl = url;
				return;
			}
			baseUrl = url.Substring(0, questionMarkIndex);
			if (questionMarkIndex == url.Length - 1)
			{
				return;
			}
			string ps = url.Substring(questionMarkIndex + 1);
			// 开始分析参数对  
			Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
			MatchCollection mc = re.Matches(ps);
			foreach (Match m in mc)
			{
				nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
			}
		}

		/// <summary>
		/// 获取表名
		/// </summary>
		/// <param name="tableName"></param>
		/// <returns></returns>
		public static string GetTableId(string tableName)
		{
			var strOut = string.Empty;

			switch (tableName)
			{
				case TableName.ProfilePaymentInfo:
					strOut = TableId.ProfilePaymentInfo; break;
				case TableName.ProfilePaymentRecord:
					strOut = TableId.ProfilePaymentRecord; break;
				case TableName.ProfileQuizInfo:
					strOut = TableId.ProfileQuizInfo; break;
				case TableName.ProfileRecommendRecord:
					strOut = TableId.ProfileRecommendRecord; break;
				case TableName.ProfileAwardsInfo:
					strOut = TableId.ProfileAwardsInfo; break;
				case TableName.ProfileHotelInfo:
					strOut = TableId.ProfileHotelInfo; break;
				case TableName.ProfileTrafficInfo:
					strOut = TableId.ProfileTrafficInfo; break;
				case TableName.ConferenceMaster:
					strOut = TableId.ConferenceMaster; break;
				case TableName.ConferenceFunctionMaster:
					strOut = TableId.ConferenceFunctionMaster; break;
				case TableName.ConferencePrintMaster:
					strOut = TableId.ConferencePrintMaster; break;
				case TableName.ConferenceAttendenceForm:
					strOut = TableId.ConferenceAttendenceForm; break;
				case TableName.ConferenceAttendenceInfo:
					strOut = TableId.ConferenceAttendenceInfo; break;
				case TableName.ConferencePayStatusInfo:
					strOut = TableId.ConferencePayStatusInfo; break;
				case TableName.TransferEvidenceMaster:
					strOut = TableId.TransferEvidenceMaster; break;
				case TableName.VisaInfo:
					strOut = TableId.VisaInfo; break;
				case TableName.ConcurrentEventMaster:
					strOut = TableId.ConcurrentEventMaster; break;
				case TableName.FeeConcurrentEventMaster:
					strOut = TableId.FeeConcurrentEventMaster; break;
				case TableName.TitleMaster:
					strOut = TableId.TitleMaster; break;
				case TableName.AttendenceIdentityMaster:
					strOut = TableId.AttendenceIdentityMaster; break;
				case TableName.ConferencePaymentMaster:
					strOut = TableId.ConferencePaymentMaster; break;
				case TableName.AlipayMaster:
					strOut = TableId.AlipayMaster; break;
				case TableName.EpayMaster:
					strOut = TableId.EpayMaster; break;
				case TableName.FeeAttendenceMaster:
					strOut = TableId.FeeAttendenceMaster; break;
				case TableName.FeePageMaster:
					strOut = TableId.FeePageMaster; break;
				case TableName.FeeMealMaster:
					strOut = TableId.FeeMealMaster; break;
				case TableName.FeeOtherMaster:
					strOut = TableId.FeeOtherMaster; break;
				case TableName.ConferenceInvoiceMaster:
					strOut = TableId.ConferenceInvoiceMaster; break;
				case TableName.ConferenceContributeForm:
					strOut = TableId.ConferenceContributeForm; break;
				case TableName.ConferenceContributeInfo:
					strOut = TableId.ConferenceContributeInfo; break;
				case TableName.AuthorInfo:
					strOut = TableId.AuthorInfo; break;
				case TableName.AffiliationInfo:
					strOut = TableId.AffiliationInfo; break;
				case TableName.TopicMaster:
					strOut = TableId.TopicMaster; break;
				case TableName.EssayMaster:
					strOut = TableId.EssayMaster; break;
				case TableName.ReportMaster:
					strOut = TableId.ReportMaster; break;
				case TableName.JournalMaster:
					strOut = TableId.JournalMaster; break;
				case TableName.OCISMaster:
					strOut = TableId.OCISMaster; break;
				case TableName.AwardsMaster:
					strOut = TableId.AwardsMaster; break;
				case TableName.ConferenceNoticeMaster:
					strOut = TableId.ConferenceNoticeMaster; break;
				case TableName.ReviewInfo:
					strOut = TableId.ReviewInfo; break;
				case TableName.ReviewPersonMaster:
					strOut = TableId.ReviewPersonMaster; break;
				case TableName.HotelMaster:
					strOut = TableId.HotelMaster; break;
				case TableName.RoomMaster:
					strOut = TableId.RoomMaster; break;
				case TableName.CheckinInfo:
					strOut = TableId.CheckinInfo; break;
				case TableName.TrafficMaster:
					strOut = TableId.TrafficMaster; break;
				case TableName.MenuMaster:
					strOut = TableId.MenuMaster; break;
				case TableName.NewsListInfo:
					strOut = TableId.NewsListInfo; break;
				case TableName.NewsInfo:
					strOut = TableId.NewsInfo; break;
				case TableName.QuizMaster:
					strOut = TableId.QuizMaster; break;
				case TableName.QuestionMaster:
					strOut = TableId.QuestionMaster; break;
				case TableName.AnswerMaster:
					strOut = TableId.AnswerMaster; break;
				case TableName.FeedbackInfo:
					strOut = TableId.FeedbackInfo; break;
				case TableName.ConferenceMailServerMaster:
					strOut = TableId.ConferenceMailServerMaster; break;
				case TableName.ConferenceMailMaster:
					strOut = TableId.ConferenceMailMaster; break;
				case TableName.ConferenceUserGroupMaster:
					strOut = TableId.ConferenceUserGroupMaster; break;
				case TableName.ConferenceRoleMaster:
					strOut = TableId.ConferenceRoleMaster; break;
				case TableName.ConferenceActionMaster:
					strOut = TableId.ConferenceActionMaster; break;
				case TableName.ConferenceUserAndGroupRelation:
					strOut = TableId.ConferenceUserAndGroupRelation; break;
				case TableName.ConferenceUserAndRoleRelation:
					strOut = TableId.ConferenceUserAndRoleRelation; break;
				case TableName.ConferenceGroupAndRoleRelation:
					strOut = TableId.ConferenceGroupAndRoleRelation; break;
				case TableName.ConferenceRoleAndActionRelation:
					strOut = TableId.ConferenceRoleAndActionRelation; break;
				case TableName.ScheduleMaster:
					strOut = TableId.ScheduleMaster; break;
				case TableName.ScheduleEventMaster:
					strOut = TableId.ScheduleEventMaster; break;
				case TableName.ScheduleDateMaster:
					strOut = TableId.ScheduleDateMaster; break;
				case TableName.ScheduleTopicMaster:
					strOut = TableId.ScheduleTopicMaster; break;
				case TableName.ScheduleInfo:
					strOut = TableId.ScheduleInfo; break;
				case TableName.SysMailServerMaster:
					strOut = TableId.SysMailServerMaster; break;
				case TableName.SysPaymentMaster:
					strOut = TableId.SysPaymentMaster; break;
				case TableName.SysConferenceModelMaster:
					strOut = TableId.SysConferenceModelMaster; break;
				case TableName.SysFunctionMaster:
					strOut = TableId.SysFunctionMaster; break;
				case TableName.SysUserMaster:
					strOut = TableId.SysUserMaster; break;
				case TableName.SysUserMasterEn:
					strOut = TableId.SysUserMasterEn; break;
				case TableName.SysUserGroupMaster:
					strOut = TableId.SysUserGroupMaster; break;
				case TableName.SysRoleMaster:
					strOut = TableId.SysRoleMaster; break;
				case TableName.SysActionMaster:
					strOut = TableId.SysActionMaster; break;
				case TableName.SysUserAndGroupRelation:
					strOut = TableId.SysUserAndGroupRelation; break;
				case TableName.SysUserAndRoleRelation:
					strOut = TableId.SysUserAndRoleRelation; break;
				case TableName.SysGroupAndRoleRelation:
					strOut = TableId.SysGroupAndRoleRelation; break;
				case TableName.SysRoleAndActionRelation:
					strOut = TableId.SysRoleAndActionRelation; break;
				case TableName.LogInfo:
					strOut = TableId.LogInfo; break;
				case TableName.ContributeMaster:
					strOut = TableId.ContributeMaster; break;
				case TableName.AttendenceMaster:
					strOut = TableId.AttendenceMaster; break;
				case TableName.SysMailMaster:
					strOut = TableId.SysMailMaster; break;					
				case TableName.LocationMaster:
					strOut = TableId.LocationMaster; break;
				case TableName.CareerMaster:
					strOut = TableId.CareerMaster; break;
				case TableName.DegreeMaster:
					strOut = TableId.DegreeMaster; break;
				case TableName.InvoiceMaster:
					strOut = TableId.InvoiceMaster; break;
				case TableName.VersionInfo:
					strOut = TableId.VersionInfo; break;
			}

			return DateTime.Now.ToString("yyyyMMdd") + strHyphen +
					strOut + strHyphen + GetRandom();
		}

		/// <summary>
		/// 登录画面
		/// </summary>
		/// <returns></returns>
		public static LoginViewModel GetLoginModel()
		{
			var dbContext = new CISEntities();
			var sql = from newListInfo in dbContext.NewsListInfo.AsNoTracking()
				       .Where(x => x.Status == Status.正常 && x.NewsListName == Login)
				  join newInfo in dbContext.NewsInfo.AsNoTracking().Where(x => x.Status == Status.正常 && !string.IsNullOrEmpty(x.MainPic))
				    on newListInfo.ID equals newInfo.NewsListId
				  join conferenceInfo in dbContext.ConferenceMaster.AsNoTracking().Where(x => x.Status == Status.正常 && x.ConferenceName == DefaultConference)
				    on newListInfo.ConferenceId equals conferenceInfo.ID
				  orderby newInfo.Sort ascending, newInfo.UpdateDate descending
				  select new
				  {
					  ID = newInfo.ID,
					  Sort = newInfo.Sort,
					  Link = newInfo.Link,
				  };

			var sqlResult = sql.ToList();

			var model = new LoginViewModel();
			model.SliderList = sqlResult.Select(x => new SliderModel
			{
				id = x.ID,
				link = x.Link
			}).ToList();

			return model;
		}

		/// <summary>
		/// 结束日期加时间
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public static DateTime? ConvertEndDate(DateTime? input)
		{
			if (input == null)
			{
				return null;
			}
			return new DateTime(input.Value.Year, input.Value.Month, input.Value.Day, 23, 59, 59);
		}

		/// <summary>
		/// 转int
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static int ObjectToInt(object obj)
		{
			if (obj == null)
			{
				return 0;
			}

			string str = obj.ToString();
			int iOut = 0;
			if (int.TryParse(str, out iOut))
			{
				return iOut;
			}
			else
			{
				return 0;
			}
		}

		/// <summary>
		/// 转double
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static double ObjectToDouble(object obj)
		{
			if (obj == null)
			{
				return 0;
			}

			string str = obj.ToString();
			double dOut = 0;
			if (double.TryParse(str, out dOut))
			{
				return dOut;
			}
			else
			{
				return 0;
			}
		}

		/// <summary>
		/// 根据ID获取名字字符串
		/// </summary>
		/// <param name="strIds"></param>
		/// <param name="type"></param>
		/// <param name="language"></param>
		/// <returns></returns>
		public static string GetNameFromIdList(string strIds, string type, string language = Language.Cn)
		{
			if (!string.IsNullOrEmpty(strIds))
			{
				var idList = strIds.Split(chrSemicolon);
				var dbContext = new CISEntities();
				var strOutput = string.Empty;

				if (type == "essay")
				{
					foreach (var id in idList)
					{
						if (!string.IsNullOrEmpty(id))
						{
							var result = dbContext.ConferenceContributeInfo.FirstOrDefault(x => id == x.ID.ToString());
							if (!string.IsNullOrEmpty(strOutput))
							{
								strOutput += strSemicolon;
							}
							strOutput += result?.EssayTitle;
						}
					}
				}
				else if (type == "topic")
				{
					foreach (var id in idList)
					{
						if (!string.IsNullOrEmpty(id))
						{
							var result = dbContext.TopicMaster.FirstOrDefault(x => x.Status == Status.正常 && id == x.ID.ToString());
							if (!string.IsNullOrEmpty(strOutput))
							{
								strOutput += strSemicolon;
							}
							strOutput += result?.TopicName;
						}
					}
				}
				else if (type == "otherFee")
				{
					foreach (var id in idList)
					{
						if (!string.IsNullOrEmpty(id))
						{
							var result = dbContext.FeeOtherMaster.FirstOrDefault(x => x.Status == Status.正常 && id == x.ID.ToString());
							if (!string.IsNullOrEmpty(strOutput))
							{
								strOutput += strSemicolon;
							}
							strOutput += result?.FeeName;
						}
					}
				}
				else if (type == "ocis")
				{
					foreach (var id in idList)
					{
						if (!string.IsNullOrEmpty(id))
						{
							var result = dbContext.OCISMaster.FirstOrDefault(x => x.Status == Status.正常 && id == x.ID.ToString());
							if (!string.IsNullOrEmpty(strOutput))
							{
								strOutput += strSemicolon;
							}
							strOutput += result?.OCISName;

						}
					}
				}
				else if (type == "career")
				{
					foreach (var id in idList)
					{
						if (!string.IsNullOrEmpty(id))
						{
							var result = dbContext.CareerMaster.FirstOrDefault(x => id == x.ID.ToString());

							if (!string.IsNullOrEmpty(strOutput))
							{
								strOutput += strSemicolon;
							}
							strOutput += language == Language.Cn ? result?.CareerName : result?.CareerNameEn;
						}
					}
				}
				var strName = strOutput;

				return strName;
			}
			else
			{
				return string.Empty;
			}
		}

		/// <summary>
		/// 根据会议ID获取会议功能
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <returns></returns>
		public static List<string> GetConferenceFunctionIdList(string conferenceId)
		{
			var dbContext = new CISEntities();
			return dbContext.ConferenceFunctionMaster.AsNoTracking()
					.Where(x => x.Status == Status.正常 &&
						x.ConferenceId == conferenceId)
					.Join(dbContext.SysFunctionMaster.AsNoTracking()
						.Where(x => x.Status == Status.正常),
						function => function.FunctionId,
						sys => sys.ID,
						(function, sys) => new
						{
							FunctionId = function.FunctionId
						}
					)
					.Select(x => x.FunctionId)
					.ToList();
		}

		/// <summary>
		/// 中英文的日期格式设置
		/// </summary>
		/// <param name="date"></param>
		/// <param name="language"></param>
		/// <returns></returns>
		public static string SetDate(DateTime? date, string language)
		{
			if (!date.HasValue)
			{
				return string.Empty;
			}
			if (language == Language.En)
			{
				return date.Value.ToString("MM/dd/yyyy");
			}
			else
			{
				return date.Value.ToString("yyyy-MM-dd");
			}
		}

		/// <summary>
		/// 中英文的姓名格式设置
		/// </summary>
		/// <param name="familyName"></param>
		/// <param name="firstName"></param>
		/// <param name="language"></param>
		/// <returns></returns>
		public static string SetFullName(string familyName, string firstName, string language)
		{
			if (language == Language.En)
			{
				return firstName + " " + familyName;
			}
			else
			{
				return familyName + firstName;
			}
		}

		/// <summary>
		/// 生成二维码
		/// </summary>
		/// <param name="strInput"></param>
		/// <param name="pfolder"></param>
		/// <param name="folder"></param>
		/// <returns></returns>
		public static string CreateQRCode(string strInput, string pfolder, string folder)
		{
			string enCodeString = strInput.PadLeft(10, chrZero);
			QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
			qrCodeEncoder.QRCodeScale = 3;
			System.Drawing.Bitmap image = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);

			var dt = DateTime.Now;
			string fileName = dt.ToString("yyyyMMddHHmmssfff") + strHyphen + GetRandom() + ".jpg";
			var pFullPath = Path.Combine(pfolder, fileName);

			var saveFileTask = Task.Run(() =>
			{
				if (!Directory.Exists(pfolder))
				{
					Directory.CreateDirectory(pfolder);
				}

				image.Save(pFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
			});
			Task.WaitAll(saveFileTask);

			return Path.Combine(folder, fileName);
		}

		/// <summary>
		/// 生成条形码
		/// </summary>
		/// <param name="strInput"></param>
		/// <param name="pfolder"></param>
		/// <param name="folder"></param>
		/// <returns></returns>
		public static string CreateBarCode(string strInput, string pfolder, string folder)
		{
			System.Drawing.Image image = null;
			BarcodeLib.Barcode b = new BarcodeLib.Barcode();
			b.BackColor = System.Drawing.Color.White;
			b.ForeColor = System.Drawing.Color.Black;
			b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
			b.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
			b.Height = 30;
			b.Width = 150;

			string sss = strInput.Substring(strInput.LastIndexOf(strHyphen) + 1);
			image = b.Encode(BarcodeLib.TYPE.CODE128, sss);

			var dt = DateTime.Now;
			string fileName = dt.ToString("yyyyMMddHHmmssfff") + strHyphen + GetRandom() + ".jpg";
			var pFullPath = Path.Combine(pfolder, fileName);

			var saveFileTask = Task.Run(() =>
			{
				if (!Directory.Exists(pfolder))
				{
					Directory.CreateDirectory(pfolder);
				}

				image.Save(pFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
			});
			Task.WaitAll(saveFileTask);

			return Path.Combine(folder, fileName);
		}

		/// <summary>
		/// 随机数
		/// </summary>
		/// <returns></returns>
		public static string GetRandom()
		{
			var str = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper();
			return str;
		}

		/// <summary>
		/// 稿件编号採番
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <returns></returns>
		public static string GetNewContributeId(string conferenceId)
		{
			var dbContext = new CISEntities();
			var nickName = dbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefault(x => x.Status == Status.正常 &&
						x.ID == conferenceId).ConferenceNickName;

			var year = DateTime.Now.Year.ToString();

			var lastContribute = dbContext.ConferenceContributeInfo.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceId &&
						x.ID.Contains(nickName + strHyphen + year + strHyphen))
					.OrderByDescending(x => x.CreateDate)
					.FirstOrDefault();

			if (lastContribute == null)
			{
				return nickName + strHyphen + year + strHyphen + 1.ToString().PadLeft(6, chrZero);
			}

			var lastId = lastContribute.ID;
			var lastIdNum = Convert.ToInt32(lastId.Substring(lastId.Length - 6).TrimStart(chrZero));

			return nickName + strHyphen + year + strHyphen + (lastIdNum + 1).ToString().PadLeft(6, chrZero);
		}

		/// <summary>
		/// 根据参会身份获取同期活动字符串
		/// </summary>
		/// <param name="concurrentEventId"></param>
		/// <param name="IsAllIdentity"></param>
		/// <param name="currency"></param>
		/// <returns></returns>
		public static string GetFeeAndIdentity(string concurrentEventId, bool? IsAllIdentity, string currency)
		{
			var dbContext = new CISEntities();
			var result = dbContext.FeeConcurrentEventMaster.AsNoTracking()
					.Where(x => x.Status == Status.正常 && x.ConcurrentEventId == concurrentEventId && x.Currency == currency)
						.OrderBy(x => x.Sort)
						.ToList();
			var returnStr = string.Empty;
			result.ForEach(x =>
			{
				var price = string.Empty;
				if (x.Currency == Currency.美元)
				{
					price = x.Price + Resources.DollarPerPerson;
				}
				else
				{
					price = x.Price + Resources.RmbPerPerson;
				}
				var identity = dbContext.AttendenceIdentityMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.AttendenceIdentityId)?.IdentityName;
				if (IsAllIdentity.Value)
				{
					if (string.IsNullOrEmpty(returnStr))
					{
						returnStr += price + chrSpace + strLeftBracket + identity + strRightBracket;
					}
					else
					{
						returnStr += "  |  " + price + chrSpace + strLeftBracket + identity + strRightBracket;
					}
				}
				else
				{
					returnStr += price + chrSpace + strLeftBracket + Resources.ApplicableForAll + strRightBracket;
				}
			});
			return returnStr;
		}

		/// <summary>
		/// 根据参会身份判断是否有同期活动
		/// </summary>
		/// <param name="concurrentEventId"></param>
		/// <param name="identity"></param>
		/// <param name="currency"></param>
		/// <returns></returns>
		public static bool HasEvent(string concurrentEventId, string identity, string currency)
		{
			var dbContext = new CISEntities();
			var result = dbContext.FeeConcurrentEventMaster.AsNoTracking()
					.Where(x => x.Status == Status.正常 && x.ConcurrentEventId == concurrentEventId && x.Currency == currency).ToList();

			return result.Any(x => x.AttendenceIdentityId == ApplicableForAll || x.AttendenceIdentityId == identity);
		}

		/// <summary>
		/// 去除html符号
		/// </summary>
		/// <param name="strHtml"></param>
		/// <returns></returns>
		public static string GetNoHtml(string strHtml)
		{
			strHtml = strHtml.Replace("&nbsp;", "");
			//删除脚本   
			strHtml = Regex.Replace(strHtml, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
			//删除HTML   
			strHtml = Regex.Replace(strHtml, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

			//替换中文引号
			strHtml = strHtml.Replace("&ldquo;", "“");
			strHtml = strHtml.Replace("&rdquo;", "”");

			strHtml = Regex.Replace(strHtml, @"-->", "", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"<!--.*", "", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(quot|#34);", "/", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(iexcl|#161);", "/xa1", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(cent|#162);", "/xa2", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(pound|#163);", "/xa3", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&(copy|#169);", "/xa9", RegexOptions.IgnoreCase);
			strHtml = Regex.Replace(strHtml, @"&#(/d+);", "", RegexOptions.IgnoreCase);
			//替换掉 < 和 > 标记
			strHtml = strHtml.Replace("<", "");
			strHtml = strHtml.Replace(">", "");
			strHtml = strHtml.Replace("/r/n", "");

			strHtml = strHtml.Replace("&Alpha;", "Α");
			strHtml = strHtml.Replace("&Beta;", "Β");
			strHtml = strHtml.Replace("&Gamma;", "Γ");
			strHtml = strHtml.Replace("&Delta;", "Δ");
			strHtml = strHtml.Replace("&Epsilon;", "Ε");
			strHtml = strHtml.Replace("&Zeta;", "Ζ");
			strHtml = strHtml.Replace("&Eta;", "Η");
			strHtml = strHtml.Replace("&Theta;", "Θ");
			strHtml = strHtml.Replace("&Iota;", "Ι");
			strHtml = strHtml.Replace("&Kappa;", "Κ");
			strHtml = strHtml.Replace("&Lambda;", "Λ");
			strHtml = strHtml.Replace("&Mu;", "Μ");
			strHtml = strHtml.Replace("&Nu;", "Ν");
			strHtml = strHtml.Replace("&Xi;", "Ξ");
			strHtml = strHtml.Replace("&Omicron;", "Ο");
			strHtml = strHtml.Replace("&Pi;", "Π");
			strHtml = strHtml.Replace("&Rho;", "Ρ");
			strHtml = strHtml.Replace("&Sigma;", "Σ");
			strHtml = strHtml.Replace("&Tau;", "Τ");
			strHtml = strHtml.Replace("&Upsilon;", "Υ");
			strHtml = strHtml.Replace("&Phi;", "Φ");
			strHtml = strHtml.Replace("&Chi;", "Χ");
			strHtml = strHtml.Replace("&Psi;", "Ψ");
			strHtml = strHtml.Replace("&Omega;", "Ω");
			strHtml = strHtml.Replace("&alpha;", "α");
			strHtml = strHtml.Replace("&beta;", "β");
			strHtml = strHtml.Replace("&gamma;", "γ");
			strHtml = strHtml.Replace("&delta;", "δ");
			strHtml = strHtml.Replace("&epsilon;", "ε");
			strHtml = strHtml.Replace("&zeta;", "ζ");
			strHtml = strHtml.Replace("&eta;", "η");
			strHtml = strHtml.Replace("&theta;", "θ");
			strHtml = strHtml.Replace("&iota;", "ι");
			strHtml = strHtml.Replace("&kappa;", "κ");
			strHtml = strHtml.Replace("&lambda;", "λ");
			strHtml = strHtml.Replace("&mu;", "μ");
			strHtml = strHtml.Replace("&nu;", "ν");
			strHtml = strHtml.Replace("&xi;", "ξ");
			strHtml = strHtml.Replace("&omicron;", "ο");
			strHtml = strHtml.Replace("&pi;", "π");
			strHtml = strHtml.Replace("&rho;", "ρ");
			strHtml = strHtml.Replace("&sigmaf;", "ς");
			strHtml = strHtml.Replace("&sigma;", "σ");
			strHtml = strHtml.Replace("&tau;", "τ");
			strHtml = strHtml.Replace("&upsilon;", "υ");
			strHtml = strHtml.Replace("&phi;", "φ");
			strHtml = strHtml.Replace("&chi;", "χ");
			strHtml = strHtml.Replace("&loz;", "◊");
			strHtml = strHtml.Replace("&psi;", "ψ");
			strHtml = strHtml.Replace("&omega;", "ω");
			strHtml = strHtml.Replace("&thetasym;", "ϑ");
			strHtml = strHtml.Replace("&upsih;", "ϒ");
			strHtml = strHtml.Replace("&piv;", "ϖ");
			strHtml = strHtml.Replace("&bull;", "•");
			strHtml = strHtml.Replace("&hellip;", "…");
			strHtml = strHtml.Replace("&prime;", "′");
			strHtml = strHtml.Replace("&Prime;", "″");
			strHtml = strHtml.Replace("&oline;", "‾");
			strHtml = strHtml.Replace("&frasl;", "⁄");
			strHtml = strHtml.Replace("&image;", "ℑ");
			strHtml = strHtml.Replace("&weierp;", "℘");
			strHtml = strHtml.Replace("&real;", "ℜ");
			strHtml = strHtml.Replace("&trade;", "");
			strHtml = strHtml.Replace("&alefsym;", "ℵ");
			strHtml = strHtml.Replace("&larr;", "←");
			strHtml = strHtml.Replace("&uarr;", "↑");
			strHtml = strHtml.Replace("&rarr;", "→");
			strHtml = strHtml.Replace("&darr;", "↓");
			strHtml = strHtml.Replace("&harr;", "");
			strHtml = strHtml.Replace("&crarr;", "↵");
			strHtml = strHtml.Replace("&lArr;", "⇐");
			strHtml = strHtml.Replace("&uArr;", "⇑");
			strHtml = strHtml.Replace("&rArr;", "⇒");
			strHtml = strHtml.Replace("&dArr;", "⇓");
			strHtml = strHtml.Replace("&hArr;", "⇔");
			strHtml = strHtml.Replace("&forall;", "∀");
			strHtml = strHtml.Replace("&part;", "∂");
			strHtml = strHtml.Replace("&exist;", "∃");
			strHtml = strHtml.Replace("&empty;", "∅");
			strHtml = strHtml.Replace("&nabla;", "∇");
			strHtml = strHtml.Replace("&isin;", "∈");
			strHtml = strHtml.Replace("&notin;", "∉");
			strHtml = strHtml.Replace("&ni;", "∋");
			strHtml = strHtml.Replace("&prod;", "∏");
			strHtml = strHtml.Replace("&minus;", "−");
			strHtml = strHtml.Replace("&sum;", "∑");
			strHtml = strHtml.Replace("&lowast;", "∗");
			strHtml = strHtml.Replace("&radic;", "√");
			strHtml = strHtml.Replace("&prop;", "∝");
			strHtml = strHtml.Replace("&infin;", "∞");
			strHtml = strHtml.Replace("&ang;", "∠");
			strHtml = strHtml.Replace("&cap;", "∩");
			strHtml = strHtml.Replace("&cup;", "∪");
			strHtml = strHtml.Replace("&int;", "∫");
			strHtml = strHtml.Replace("&there4;", "∴");
			strHtml = strHtml.Replace("&sim;", "∼");
			strHtml = strHtml.Replace("&cong;", "≅");
			strHtml = strHtml.Replace("&asymp;", "≈");
			strHtml = strHtml.Replace("&ne;", "≠");
			strHtml = strHtml.Replace("&equiv;", "≡");
			strHtml = strHtml.Replace("&le;", "≤");
			strHtml = strHtml.Replace("&ge;", "≥");
			strHtml = strHtml.Replace("&sub;", "⊂");
			strHtml = strHtml.Replace("&sup;", "⊃");
			strHtml = strHtml.Replace("&nsub;", "⊄");
			strHtml = strHtml.Replace("&sube;", "⊆");
			strHtml = strHtml.Replace("&supe;", "⊇");
			strHtml = strHtml.Replace("&oplus;", "⊕");
			strHtml = strHtml.Replace("&otimes;", "⊗");
			strHtml = strHtml.Replace("&and;", "∧");
			strHtml = strHtml.Replace("&perp;", "⊥");
			strHtml = strHtml.Replace("&or;", "∨");
			strHtml = strHtml.Replace("&sdot;", "⋅");
			strHtml = strHtml.Replace("&lceil;", "⌈");
			strHtml = strHtml.Replace("&rceil;", "⌉");
			strHtml = strHtml.Replace("&lfloor;", "⌊");
			strHtml = strHtml.Replace("&rfloor;", "⌋");
			strHtml = strHtml.Replace("&spades;", "");
			strHtml = strHtml.Replace("&clubs;", "");
			strHtml = strHtml.Replace("&hearts;", "");
			strHtml = strHtml.Replace("&diams;", "");
			strHtml = strHtml.Replace("&nbsp;", "");
			strHtml = strHtml.Replace("&iexcl;", "¡");
			strHtml = strHtml.Replace("&cent;", "¢");
			strHtml = strHtml.Replace("&pound;", "£");
			strHtml = strHtml.Replace("&curren;", "¤");
			strHtml = strHtml.Replace("&yen;", "¥");
			strHtml = strHtml.Replace("&brvbar;", "¦");
			strHtml = strHtml.Replace("&sect;", "§");
			strHtml = strHtml.Replace("&uml;", "¨");
			strHtml = strHtml.Replace("&copy;", "");
			strHtml = strHtml.Replace("&ordf;", "ª");
			strHtml = strHtml.Replace("&laquo;", "«");
			strHtml = strHtml.Replace("&not;", "¬");
			strHtml = strHtml.Replace("&shy;", "");
			strHtml = strHtml.Replace("&reg;", "");
			strHtml = strHtml.Replace("&macr;", "¯");
			strHtml = strHtml.Replace("&deg;", "°");
			strHtml = strHtml.Replace("&plusmn;", "±");
			strHtml = strHtml.Replace("&sup2;", "²");
			strHtml = strHtml.Replace("&sup3;", "³");
			strHtml = strHtml.Replace("&acute;", "´");
			strHtml = strHtml.Replace("&micro;", "µ");
			strHtml = strHtml.Replace("&quot;", "\"");
			strHtml = strHtml.Replace("&amp;", "&");
			strHtml = strHtml.Replace("&lt;", "<");
			strHtml = strHtml.Replace("&gt;", ">");
			strHtml = strHtml.Replace("/r/n", "");
			strHtml = strHtml.Replace("&ldquo;", "“");
			strHtml = strHtml.Replace("&rdquo;", "”");
			strHtml = strHtml.Replace("&ndash;", "–");


			//返回去掉html标记的字符串
			return strHtml;
		}

		/// <summary>
		/// 根据稿件编号获取稿件的所有作者+公司编号
		/// </summary>
		/// <param name="contributeId"></param>
		/// <returns>返回一个list，list里有两个元素，第一个是所有作者拼成的string，第二个是所有单位拼成的string</returns>
		public static List<string> GetAuthorFormat(string contributeId)
		{
			var dbContext = new CISEntities();
			var conferenceContributeInfo = dbContext.ConferenceContributeInfo.AsNoTracking().FirstOrDefault(x => x.ID == contributeId);
			if (conferenceContributeInfo == null)
			{
				var emptyList = new List<string>();
				emptyList.Add(string.Empty);
				emptyList.Add(string.Empty);
				return emptyList;
			}
			var conferenceMaster = dbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == conferenceContributeInfo.ConferenceId);
			if (conferenceMaster == null)
			{
				var emptyList = new List<string>();
				emptyList.Add(string.Empty);
				emptyList.Add(string.Empty);
				return emptyList;
			}

			var authorInfoList = dbContext.AuthorInfo.AsNoTracking()
					.Where(x => x.ContributeId == contributeId && x.Status == Status.正常)
					.OrderBy(x => x.Sort)
					.ThenBy(x => x.CreateDate)
					.ToList();

			var affiliationInfo = dbContext.AffiliationInfo.AsNoTracking()
					.Where(x => x.ContributeId == contributeId && x.Status == Status.正常)
					.OrderBy(x => x.CreateDate)
					.ThenBy(x => x.Sort)
					.ToList();

			List<string> affiliationInfoList = new List<string>();
			List<string> countryList = new List<string>();
			for (var index = 0; index < affiliationInfo.Count(); index++)
			{
				if (!affiliationInfoList.Contains(affiliationInfo[index].Affiliation))
				{
					affiliationInfoList.Add(affiliationInfo[index].Affiliation);
					var tempCountryId = affiliationInfo[index].Country;
					var locationMaster = dbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == tempCountryId);
					if (locationMaster != null)
					{
						countryList.Add(locationMaster.NameEn);
					}
					else
					{
						countryList.Add(string.Empty);
					}
				}
			}

			var strAuthor = string.Empty;

			for (var index = 0; index < authorInfoList.Count; index++)
			{
				strAuthor += authorInfoList[index].FullName;
				var strTemp = string.Empty;
				var strMail = authorInfoList[index].Mail;

				var authorAffiliationList = dbContext.AffiliationInfo.AsNoTracking()
						.Where(x => x.ContributeId == contributeId &&
							x.Status == Status.正常 &&
							x.Mail == strMail)
						.OrderBy(x => x.CreateDate)
						.ThenBy(x => x.Sort)
						.ToList();

				var sortList = new List<int>();
				for (var index2 = 0; index2 < authorAffiliationList.Count; index2++)
				{
					var num = affiliationInfoList.IndexOf(authorAffiliationList[index2].Affiliation);
					sortList.Add(num + 1);
				}
				sortList.Sort();//把公司编号从小到大排序
				strTemp = string.Join(strComma, sortList);

				if (authorInfoList[index].IsContactAuthor)
				{
					strTemp += strStar;
				}

				strAuthor += strHtmlSupStart + strTemp + strHtmlSupEnd;
				if (index != authorInfoList.Count - 1)
				{
					if (conferenceMaster.IsInternational)
					{
						strAuthor += strComma + chrSpace;
					}
					else
					{
						strAuthor += strCommaCn;
					}
				}
			}

			var strAffiliation = string.Empty;
			for (var index3 = 0; index3 < affiliationInfoList.Count(); index3++)
			{
				if (!string.IsNullOrEmpty(strAffiliation))
				{
					if (conferenceMaster.IsInternational)
					{
						strAffiliation += strSemicolon + chrSpace;
					}
					else
					{
						strAffiliation += strSemicolonCN;
					}
				}
				strAffiliation += (index3 + 1).ToString() + strDot + affiliationInfoList[index3];
				if (conferenceMaster.IsInternational)
				{
					strAffiliation += strComma + chrSpace;
					strAffiliation += countryList[index3];
				}
			}

			var returnList = new List<string>();
			returnList.Add(strAuthor);
			returnList.Add(strAffiliation);
			return returnList;
		}

		/// <summary>
		/// 获取虚拟房号
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <param name="count"></param>
		/// <param name="list"></param>
		/// <returns></returns>
		public static List<int> GetDummyRoomNum(string conferenceId, int count, List<int> list)
		{
			var dbContext = new CISEntities();
			var dummyRoomNum = dbContext.ProfileHotelInfo.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceId)
					.Max(x => x.DummyRoomNum);

			var ret = new List<int>();
			if (list.Count > 0)
			{
				var tmp = list.Last() + 1;
				for (var index = 0; index < count; index++)
				{
					ret.Add(tmp);
					tmp++;
				}
			}
			else
			{
				var tmp = dummyRoomNum.HasValue ? dummyRoomNum.Value + 1 : initDummyNum;
				for (var index = 0; index < count; index++)
				{
					ret.Add(tmp);
					tmp++;
				}
			}
			return ret;
		}

		/// <summary>
		/// 获取订单编号
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <param name="orderType"></param>
		/// <returns></returns>
		public static string GetOrderNum(string conferenceId, string orderType)
		{
			var dbContext = new CISEntities();
			var nickName = dbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefault(x => x.Status == Status.正常 &&
						x.ID == conferenceId).ConferenceNickName;

			var monthDay = DateTime.Now.ToString("MMdd");

			ValidatedCode v = new ValidatedCode();
			string code = v.CreateVerifyCode();

			var orderNum = string.Empty;
			if (orderType == OrderType.酒店)
			{
				orderNum = dbContext.ProfileHotelInfo.AsNoTracking()
						.Where(x => x.ConferenceId == conferenceId)
						.Max(x => x.OrderNum);
			}
			else
			{
				orderNum = dbContext.ProfileTrafficInfo.AsNoTracking()
						.Where(x => x.ConferenceId == conferenceId)
						.Max(x => x.OrderNum);
			}

			var newOrderNum = initOrderNum;
			if (!string.IsNullOrEmpty(orderNum))
			{
				var str = orderNum.Substring(orderNum.Length - 8, 4);
				newOrderNum = (Convert.ToInt32(str) + 1).ToString().PadLeft(4, chrZero);
			}
			return nickName + monthDay + newOrderNum + code;
		}

		/// <summary>
		/// 根据参会Id获取用户所选的同期活动适用哪些参会身份
		/// </summary>
		/// <param name="attendId"></param>
		/// <returns></returns>
		public static string GetApplyIdentity(string attendId)
		{
			var returnList = new List<string>();
			var dbContext = new CISEntities();
			var tempList = new List<List<string>>();
			var conferenceAttendenceInfo = dbContext.ConferenceAttendenceInfo.AsNoTracking().FirstOrDefault(x => x.ID == attendId);
			if (conferenceAttendenceInfo != null)
			{
				var profilePaymentInfo = dbContext.ProfilePaymentInfo.AsNoTracking()
						.Where(x => x.FeeType == FeeType.同期活动费 && x.AttendenceId == attendId).ToList();
				var allIdentityList = dbContext.AttendenceIdentityMaster.AsNoTracking()
						.Where(x => x.ConferenceId == conferenceAttendenceInfo.ConferenceId &&
							x.Status == Status.正常)
						.Select(x => x.ID)
						.ToList();
				if (profilePaymentInfo.Count() > 0)
				{
					profilePaymentInfo.ForEach(x =>
					{
						var feeConcurrentEventMaster = dbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId);
						if (feeConcurrentEventMaster != null)
						{
							if (feeConcurrentEventMaster.AttendenceIdentityId != ApplicableForAll)
							{
								var eventList = dbContext.FeeConcurrentEventMaster.AsNoTracking()
										.Where(y => y.ConcurrentEventId == feeConcurrentEventMaster.ConcurrentEventId &&
											y.Currency == conferenceAttendenceInfo.Currency)
										.Select(y => y.AttendenceIdentityId).ToList();
								tempList.Add(eventList);
							}
							else if (feeConcurrentEventMaster.AttendenceIdentityId == ApplicableForAll)
							{
								tempList.Add(allIdentityList);
							}
						}
					});
				}
				if (tempList.Count() > 0)
				{
					returnList = tempList[0];
					for (int index = 0; index < tempList.Count(); index++)
					{
						returnList = returnList.Intersect(tempList[index]).ToList();
					}
				}
			}
			var returnStr = string.Empty;
			returnList.ForEach(x =>
			{
				if (string.IsNullOrEmpty(returnStr))
				{
					returnStr += x;
				}
				else
				{
					returnStr += chrComma;
					returnStr += x;
				}
			});
			return returnStr;
		}

		/// <summary>
		/// 把预订交通页面的服务类型从constvalues转换成resources
		/// </summary>
		/// <param name="serviceType"></param>
		/// <returns></returns>
		public static string ChangeTrafficTypeToResources(string serviceType)
		{
			if (serviceType == TrafficType.接机)
			{
				return Resources.ReceivingService;
			}
			else if (serviceType == TrafficType.接送机)
			{
				return Resources.ArrivalDeparturalService;
			}
			else if (serviceType == TrafficType.送机)
			{
				return Resources.DeliveryService;
			}
			else
			{
				return string.Empty;
			}
		}

		/// <summary>
		/// 根据作者的邮箱和会议id获取作者的所有单位
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <param name="mail"></param>
		/// <param name="contributeId"></param>
		/// <param name="separator"></param>
		/// <returns></returns>
		public static string GetAllAffiliation(string conferenceId, string mail, string contributeId, string separator)
		{
			var dbContext = new CISEntities();
			var affiliationList = dbContext.AffiliationInfo.AsNoTracking()
					.Where(x => x.Status == Status.正常 &&
						x.ConferenceId == conferenceId &&
						x.ContributeId == contributeId  &&
						x.Mail == mail)
					.OrderBy(x => x.Sort)
					.ThenBy(x => x.Affiliation)
					.Select(x => x.Affiliation)
					.Distinct()
					.ToList();

			var affiliation = affiliationList.Count > 0 ? string.Join(strSemicolonCN, affiliationList) : string.Empty;
			if (!string.IsNullOrEmpty(affiliation))
			{
				return separator + affiliation;
			}
			else
			{
				return affiliation;
			}
		}

		/// <summary>
		/// 根据作者的邮箱和会议id获取作者的所有单位，英文状态下要拼上国家
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <param name="mail"></param>
		/// <param name="contributeId"></param>
		/// <param name="separator"></param>
		/// <returns></returns>
		public static string GetAllAffiliationEn(string conferenceId, string mail, string contributeId, string separator)
		{
			var dbContext = new CISEntities();
			var affiliationList = dbContext.AffiliationInfo.AsNoTracking()
					.Where(x => x.Status == Status.正常 &&
						x.ConferenceId == conferenceId &&
						x.ContributeId == contributeId &&
						x.Mail == mail)
					.OrderBy(x => x.Sort)
					.ThenBy(x => x.Affiliation)
					.Select(x => new
					{
						Affiliation = x.Affiliation,
						Country = x.Country
					})
					.Distinct()
					.ToList();

			var returnStr = string.Empty;
			for (var index = 0; index < affiliationList.Count; index++)
			{
				if (!string.IsNullOrEmpty(returnStr))
				{
					returnStr += strSemicolon + chrSpace;
				}
				returnStr += affiliationList[index].Affiliation;
				if (affiliationList[index].Country.HasValue)
				{
					var countryId = affiliationList[index].Country.Value;
					var country = dbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == countryId);
					if (country != null)
					{
						returnStr += separator;
						returnStr += country.NameEn;
					}
				}
			}
			if (!string.IsNullOrEmpty(returnStr))
			{
				return separator + returnStr;
			}
			else
			{
				return returnStr;
			}
		}

		/// <summary>
		/// 根据scheduleEventId获取事件名称，是主持人日程，不是报告！！主持人要带上单位和国家
		/// </summary>
		/// <param name="scheduleEventId"></param>
		/// <returns></returns>
		public static string GetScheduleEventNameById(string scheduleEventId)
		{
			var dbContext = new CISEntities();
			var scheduleEventMaster = dbContext.ScheduleEventMaster.AsNoTracking().FirstOrDefault(x => x.ID == scheduleEventId);
			if (scheduleEventMaster == null)
			{
				return string.Empty;
			}

			if (string.IsNullOrEmpty(scheduleEventMaster.ChairmanMail))
			{
				return scheduleEventMaster.EventName;
			}
			else
			{
				var conferenceMaster = dbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == scheduleEventMaster.ConferenceId);
				if (conferenceMaster.IsInternational)
				{
					return scheduleEventMaster.EventName + GetAllAffiliationEn(scheduleEventMaster.ConferenceId, scheduleEventMaster.ChairmanMail, scheduleEventMaster.ContributeId, strComma + strSpace);
				}
				else
				{
					return scheduleEventMaster.EventName + GetAllAffiliation(scheduleEventMaster.ConferenceId, scheduleEventMaster.ChairmanMail, scheduleEventMaster.ContributeId, strCommaCn);
				}
			}
		}

		/// <summary>
		/// 获取投稿所有项目
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <returns></returns>
		public static ContributeFormModel GetContributeItem(string conferenceId)
		{
			var dbContext = new CISEntities();
			var sqlResult = dbContext.ConferenceContributeForm.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceId &&
						x.Key != 参会投稿表单.同期活动)
					.ToList();

			var result = new ContributeFormModel()
			{
				EssayTitle = sqlResult.FirstOrDefault(x => x.Key == "EssayTitle")?.DisplayName,
				Abstract = sqlResult.FirstOrDefault(x => x.Key == "Abstract")?.DisplayName,
				Keyword = sqlResult.FirstOrDefault(x => x.Key == "Keyword")?.DisplayName,
				Topic = sqlResult.FirstOrDefault(x => x.Key == "Topic")?.DisplayName,
				Essay = sqlResult.FirstOrDefault(x => x.Key == "Essay")?.DisplayName,
				Report = sqlResult.FirstOrDefault(x => x.Key == "Report")?.DisplayName,
				ProgramAbstract = sqlResult.FirstOrDefault(x => x.Key == "ProgramAbstract")?.DisplayName,
				AbstractFile = sqlResult.FirstOrDefault(x => x.Key == "AbstractFile")?.DisplayName,
				SupplementaryFile = sqlResult.FirstOrDefault(x => x.Key == "SupplementaryFile")?.DisplayName,

				IsShowAbstract = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "Abstract"),
				IsShowKeyword = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "Keyword"),
				IsShowTopic = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "Topic"),
				IsShowEssay = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "Essay"),
				IsShowReport = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "Report"),
				IsShowProgramAbstract = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "ProgramAbstract"),
				IsShowAbstractFile = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "AbstractFile"),
				IsShowSupplementaryFile = sqlResult.Any(x => x.Status == Status.正常 && x.Key == "SupplementaryFile"),

				IsShowAwards = dbContext.ConferenceFunctionMaster.AsNoTracking()
						.Any(x => x.ConferenceId == conferenceId && x.Status == Status.正常 && x.FunctionId == FunctionId.ConferenceAwards),
			};

			return result;
		}

		/// <summary>
		/// 获取参会注册自定义项目
		/// </summary>
		/// <param name="conferenceId"></param>
		/// <returns></returns>
		public static List<ConferenceFormModel> GetAttendenceCustomizeList(string conferenceId)
		{
			var dbContext = new CISEntities();

			return dbContext.ConferenceAttendenceForm.AsNoTracking()
					.Where(x => x.Status == Status.正常 && x.ConferenceId == conferenceId && x.Key.Contains("Customize"))
					.OrderBy(x => x.DisplayPage)
					.ThenBy(x => x.Sort)
					.ThenBy(x => x.DisplayName)
					.Select(x => new ConferenceFormModel
					{
						Key = x.Key,
						DisplayName = x.DisplayName,
					})
					.ToList();
		}

		/// <summary>
		/// 保存发票信息
		/// </summary>
		/// <returns></returns>
		public static bool SaveInvoiceInfo(ICISPrincipal principal, InvoiceModel model)
		{
			if (string.IsNullOrWhiteSpace(model.InvoiceTitle) || string.IsNullOrWhiteSpace(model.TaxNum))
			{
				return false;
			}

			// 发票抬头：全中文，括号，书名号
			foreach (var chr in model.InvoiceTitle)
			{
				if (!(Regex.IsMatch(chr.ToString(), @"[\u4e00-\u9fa5]")
					|| chr.ToString() == "(" || chr.ToString() == ")" 
					|| chr.ToString() == "（" || chr.ToString() == "）"
					|| chr.ToString() == "《" || chr.ToString() == "》"))
				{
					return false;
				}
			}

			// 税号：18位或15位，由数字和大写字母组合，无税号
			Match halfEngNum = Regex.Match(model.TaxNum, "^[A-Z0-9]+$");
			if (model.TaxNum != DefaultInvoice)
			{
				if (!halfEngNum.Success || (halfEngNum.Length != 15 && halfEngNum.Length != 18))
				{
					return false;
				}
			}

			var dbContext = new CISEntities();
			var result = dbContext.InvoiceMaster.AsNoTracking()
					.FirstOrDefault(x => x.InvoiceTitle == model.InvoiceTitle && x.TaxNum == model.TaxNum);

			if (result != null)
			{
				return false;
			}

			var invoiceMaster = new InvoiceMaster
			{
				ID = GetTableId(TableName.InvoiceMaster),
				InvoiceTitle = model.InvoiceTitle?.Trim(),
				TaxNum = model.TaxNum?.Trim(),
				AddressAndTel = model.AddressAndTel?.Trim(),
				Bank = model.Bank?.Trim(),
				BankAccount = model.BankAccount?.Trim(),

				Status = Status.正常,
				Sort = DefaultSort,
				Creator = principal.UserName,
				CreateIP = principal.IP,
				CreateDate = DateTime.Now
			};

			dbContext.InvoiceMaster.Add(invoiceMaster);
			dbContext.SaveChanges();

			return true;
		}

		/// <summary>
		/// 邮件内容
		/// </summary>
		/// <param name="model"></param>
		/// <returns></returns>
		public static MailMessage GetMailContent(MailModel model)
		{
			var dbContext = new CISEntities();
			var systemMail = dbContext.SysMailMaster.AsNoTracking().FirstOrDefault(x => x.Remark == model.MailRemark);
			var conferenceMail = dbContext.ConferenceMailMaster.AsNoTracking()
					.FirstOrDefault(x => x.ConferenceId == model.ConferenceId && x.Remark == model.MailRemark);

			MailMessage message = new MailMessage();
			message.IsBodyHtml = true;
			message.Subject = model.Language == Language.En ? systemMail.SubjectEn : systemMail.Subject;

			var content = model.Language == Language.En ? systemMail.ContentEn : systemMail.Content;
			content = content.Replace("{自定义内容}", conferenceMail != null ? conferenceMail.CustomDefinition : string.Empty);

			if (model.MailRemark == MailSubject.会议投稿 || model.MailRemark == MailSubject.审稿结果)
			{
				var formModel = GetContributeItem(model.ConferenceId);
				content = content.Replace("{colTitle}", formModel.EssayTitle);
				content = formModel.IsShowTopic ?
						content.Replace("{showTopic}", string.Empty).Replace("{colTopic}", formModel.Topic) :
						content.Replace("{showTopic}", "display:none;");
				content = formModel.IsShowEssay ?
						content.Replace("{showEssay}", string.Empty).Replace("{colEssay}", formModel.Essay) :
						content.Replace("{showEssay}", "display:none;");
				content = formModel.IsShowReport ?
						content.Replace("{showReport}", string.Empty).Replace("{colReport}", formModel.Report) :
						content.Replace("{showReport}", "display:none;");

				var notice = dbContext.ConferenceNoticeMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId);
				content = model.ContributationStatus == Resources.StatusReviewAccept && notice.HasAttachment && model.HasPdf ?
						content.Replace("{showAttachment}", string.Empty) :
						content.Replace("{showAttachment}", "display:none;");
			}

			if (model.IsPreview)
			{
				message.Body = content;
				return message;
			}

			if (model.MailRemark == MailSubject.缴费成功)
			{
				var tmp = string.Empty;
				for (var index = 0; index < model.PayList.Count; index++)
				{
					tmp += model.PayList[index];
					tmp += index == model.PayList.Count - 1 ? string.Empty : strHtmlNewline;
				}
				content = content.Replace("{PayDetail}", tmp);
			}
			else if (model.MailRemark == MailSubject.酒店预订)
			{
				var tmp = string.Empty;
				for (var index = 0; index < model.HotelList.Count; index++)
				{
					if (model.Language == Language.En)
					{
						tmp += "<p>Hotel Name: " + model.HotelList[index].HotelName + "</p>";
						tmp += "<p>Room Type: " + model.HotelList[index].RoomType + strComma + " " + model.HotelList[index].Price + "</p>";
						tmp += "<p>Rooms: " + model.HotelList[index].RoomNumber + "</p>";
						tmp += "<p>Guest Name: " + model.HotelList[index].GuestName + "</p>";
						tmp += "<p>Check-in: " + model.HotelList[index].CheckinDate + "</p>";
						tmp += "<p>Check-out: " + model.HotelList[index].CheckoutDate + "</p>";
						tmp += "<p>Nights: " + model.HotelList[index].CheckinDaysCount + "</p>";
					}
					else
					{
						tmp += "<p>酒店名称：" + model.HotelList[index].HotelName + "</p>";
						tmp += "<p>房间类型：" + model.HotelList[index].RoomType + strCommaCn + model.HotelList[index].Price + "</p>";
						tmp += "<p>房间数量：" + model.HotelList[index].RoomNumber + "</p>";
						tmp += "<p>客人姓名：" + model.HotelList[index].GuestName + "</p>";
						tmp += "<p>入住时间：" + model.HotelList[index].CheckinDate + "</p>";
						tmp += "<p>退房时间：" + model.HotelList[index].CheckoutDate + "</p>";
						tmp += "<p>入住天数：" + model.HotelList[index].CheckinDaysCount + "</p>";
					}
					
					tmp += index == model.HotelList.Count - 1 ? "<hr align='left' style='border: 1px solid;width:400px;' />" : "<hr align='left' style='border: 1px dashed;width:400px;' />";
				}
				content = content.Replace("{HotelDetail}", tmp);
			}
			else if (model.MailRemark == MailSubject.交通预订 || model.MailRemark == MailSubject.交通修改)
			{
				var tmp = string.Empty;
				for (var index = 0; index < model.TrafficList.Count; index++)
				{
					if (model.Language == Language.En)
					{
						tmp += model.TrafficList[index].TrafficType == TrafficType.接机 ? "<p><strong>Pick-up service</strong></p>" :
								"<p><strong>Return service</strong></p>";
						tmp += model.TrafficList[index].TrafficType == TrafficType.接机 ? "<p>Arriving Time: " + model.TrafficList[index].FlightDate + "</p>" :
								"<p>Departure Time: " + model.TrafficList[index].FlightDate + "</p>";
						tmp += "<p>Flight/Train No.: " + model.TrafficList[index].FlightNum + "</p>";
						tmp += "<p>Transport Type: " + model.TrafficList[index].TrafficName;
						tmp += model.MailRemark == MailSubject.交通预订 ? strComma + model.TrafficList[index].Fee + "</p>" : "</p>";
					}
					else
					{
						tmp += model.TrafficList[index].TrafficType == TrafficType.接机 ? "<p><strong>接机服务</strong></p>" :
								"<p><strong>送机服务</strong></p>";
						tmp += "<p>抵达时间：" + model.TrafficList[index].FlightDate + "</p>";
						tmp += "<p>航班号/车次：" + model.TrafficList[index].FlightNum + "</p>";
						tmp += "<p>接送方式：" + model.TrafficList[index].TrafficName;
						tmp += model.MailRemark == MailSubject.交通预订 ? strCommaCn + model.TrafficList[index].Fee + "</p>" : "</p>";
					}

					if (model.MailRemark == MailSubject.交通预订)
					{
						if (index == model.TrafficList.Count - 1)
						{
							tmp += "<hr align='left' style='border: 1px solid;width:400px;' />";
						}
						else if (model.TrafficList[index].Sequence != model.TrafficList[index + 1].Sequence)
						{
							tmp += "<hr align='left' style='border: 1px dashed;width:400px;' />";
						}
					}
				}
				content = content.Replace("{TrafficDetail}", tmp)
						.Replace("{TrafficStatus}", model.TrafficStatus);
			}
			else if (model.MailRemark == MailSubject.酒店修改)
			{
				content = content.Replace("{HotelStatus}", model.HotelStatus)
						.Replace("{DummyRoomNum}", model.DummyRoomNum)
						.Replace("{HotelName}", model.HotelName)
						.Replace("{RoomType}", model.RoomType)
						.Replace("{IsCombine}", model.IsCombine)
						.Replace("{GuestName}", model.GuestName)
						.Replace("{CheckinDate}", model.CheckinDate)
						.Replace("{CheckoutDate}", model.CheckoutDate);
			}

			var date = model.Language == Language.En ? DateTime.Now.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy年MM月dd日");
			message.Body = content
					.Replace("{Date}", date)
					.Replace("{UserName}", model.UserName)
					.Replace("{ActiveUrl}", model.ActiveUrl)
					.Replace("{ActiveUrlTxt}", model.ActiveUrl)
					.Replace("{Mail}", model.Mail)
					.Replace("{Password}", model.Password)
					.Replace("{ConferenceName}", model.ConferenceName)
					.Replace("{ConferenceNickName}", model.ConferenceNickName)
					.Replace("{ConferenceUrl}", model.ConferenceUrl)
					.Replace("{ContributeId}", model.ContributeId)
					.Replace("{EssayTitle}", model.EssayTitle)
					.Replace("{Topic}", model.Topic)
					.Replace("{Essay}", model.Essay)
					.Replace("{Report}", model.Report)
					.Replace("{Presenter}", model.Presenter)
					.Replace("{ContributationStatus}", model.ContributationStatus)
					.Replace("{AttendenceId}", model.AttendenceId)
					.Replace("{Recommedation}", model.Recommedation)
					.Replace("{QuizUrl}", model.QuizUrl)
					.Replace("{Status}", model.Status)
					.Replace("{Currency}", model.Currency)
					.Replace("{TotalFee}", model.TotalFee)
					.Replace("{PaymentType}", model.PaymentType)
					.Replace("{PaidStatus}", model.PaidStatus)
					.Replace("{Contact}", model.Contact)
					.Replace("{OrderNum}", model.OrderNum);

			return message;
		}

		/// <summary>
		/// 邮件支付明细
		/// </summary>
		/// <param name="attendenceId"></param>
		/// <param name="conferenceId"></param>
		/// <param name="benefitStartDate"></param>
		/// <param name="benefitEndDate"></param>
		/// <returns></returns>
		public static List<string> GetPayDetailList(string attendenceId, string conferenceId, DateTime? benefitStartDate, DateTime? benefitEndDate)
		{
			var dbContext = new CISEntities();
			var sql = from paymentInfo in dbContext.ProfilePaymentInfo.AsNoTracking()
					.Where(x => x.AttendenceId == attendenceId)
				  join attInfo in dbContext.ConferenceAttendenceInfo.AsNoTracking()
					on paymentInfo.AttendenceId equals attInfo.ID
				  orderby paymentInfo.FeeType
				  select new ProfilePayInfoModel
				  {
					  FeeType = paymentInfo.FeeType,
					  FeeId = paymentInfo.FeeId,
					  FeeName = string.Empty,
					  Count = paymentInfo.Count,
					  Currency = paymentInfo.Currency,
					  Fee = paymentInfo.Fee,
					  Discount = paymentInfo.Discount,
					  BenefitEndDate = benefitEndDate,
					  BenefitStartDate = benefitStartDate,
					  ConferenceId = conferenceId,
					  DisplayName = ""
				  };

			var sqlResult = sql.ToList();

			double? conferenceFee = 0.00;
			double? eventFee = 0.00;
			string totalCurrency = "";
			sqlResult.ForEach(x =>
			{
				if (x.FeeType == FeeType.餐费)
				{
					x.DisplayName = dbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Meal")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = dbContext.FeeMealMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == FeeType.参会费)
				{
					x.DisplayName = dbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Attendence")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = dbContext.FeeAttendenceMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).RegisterType;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == FeeType.版面费)
				{
					x.DisplayName = dbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Page")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = dbContext.FeePageMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == FeeType.其他费用)
				{
					x.DisplayName = dbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Other")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = dbContext.FeeOtherMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == FeeType.同期活动费)
				{
					x.DisplayName = dbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "ConcurrentEvent")?.DisplayName;
					var ConcurrentEventId = dbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId)?.ConcurrentEventId;
					x.FeeName = dbContext.ConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == ConcurrentEventId)?.EventName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					eventFee += Fee;
					totalCurrency = x.Currency;
				}
			});

			return sqlResult.Select(x => x.DisplayName + " " + x.FeeName + " " + x.Currency + " " + (x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount.Value.ToString("N2") : x.Fee.Value.ToString("N2"))).ToList();
		}

		#region 文件相关
		/// <summary>
		/// 判断是否含有上下标
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static bool ContainSubSup(string str)
		{
			return (str.Contains(strHtmlSupStart) && str.Contains(strHtmlSupEnd)) || (str.Contains(strHtmlSubStart) && str.Contains(strHtmlSubEnd));
		}

		#region 导出稿件的上标处理
		public static string GetSupIndexs(string str, ref List<int[]> tagIndexList)
		{
			List<int[]> sups = new List<int[]>();

			while (true)
			{
				int[] sup_pair = GetNextSupsTagsIndex(str, strHtmlSupStart);
				if (sup_pair != null)
				{
					str = RemoveNextSupTags(str, strHtmlSupStart);
					sup_pair[1] = sup_pair[1] - strHtmlSupStart.Length;
					sups.Add(sup_pair);
					continue;
				}
				if (sup_pair == null)
				{
					break;
				}
			}

			tagIndexList = sups;
			return str;
		}

		private static int[] GetNextSupsTagsIndex(string str, string tag)
		{
			int firstSupStart = str.IndexOf(tag);
			if (firstSupStart > -1)
			{
				int firstSupEnd = str.IndexOf(strHtmlSupEnd);
				if (firstSupEnd > firstSupStart)
				{
					return new int[] { firstSupStart, firstSupEnd };
				}
			}
			return null;
		}

		private static string RemoveNextSupTags(string str, string tag)
		{
			str = ReplaceFirst(str, tag, string.Empty);
			str = ReplaceFirst(str, strHtmlSupEnd, string.Empty);
			return str;
		}

		private static string ReplaceFirst(string input, string oldValue, string newValue)
		{
			Regex regEx = new Regex(oldValue, RegexOptions.Multiline);
			return regEx.Replace(input, newValue == null ? string.Empty : newValue, 1);
		}
		#endregion

		/// <summary>
		/// 摘要导出成word 的上下标改变
		/// </summary>
		/// <param name="paragraph"></param>
		/// <param name="run"></param>
		/// <param name="text"></param>
		/// <returns></returns>
		public static XWPFRun ChangeSubSupForWord(XWPFParagraph paragraph, XWPFRun run, string text)
		{
			text = text.Replace(strHtmlSupStart, SupSubNeedChange.宏银需要改变的上标开始);
			text = text.Replace(strHtmlSupEnd, SupSubNeedChange.宏银需要改变的上标结束);
			text = text.Replace(strHtmlSubStart, SupSubNeedChange.宏银需要改变的下标开始);
			text = text.Replace(strHtmlSubEnd, SupSubNeedChange.宏银需要改变的下标结束);

			text = GetNoHtml(text);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标开始, strHtmlSupStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标结束, strHtmlSupEnd);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标开始, strHtmlSubStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标结束, strHtmlSubEnd);

			do
			{
				var indexStart = text.IndexOf(strHtmlSupStart);
				var indexStart2 = text.IndexOf(strHtmlSubStart);

				var tempStart = 0;
				var type = string.Empty;

				if (indexStart != -1 && indexStart2 != -1)
				{
					if (indexStart < indexStart2)
					{
						tempStart = indexStart;
						type = "sup";
					}
					else
					{
						tempStart = indexStart2;
						type = "sub";
					}
				}
				else
				{
					if (indexStart != -1)
					{
						tempStart = indexStart;
						type = "sup";
					}
					else
					{
						tempStart = indexStart2;
						type = "sub";
					}
				}

				var tempString = text.Substring(0, tempStart);
				run = paragraph.CreateRun();
				run.SetText(tempString);
				run.FontSize = 10;
				text = text.Substring(tempStart + 5);

				var indexEnd = text.IndexOf(type == "sup" ? strHtmlSupEnd : strHtmlSubEnd);
				var tmp = text.Substring(0, indexEnd);
				run = paragraph.CreateRun();
				run.FontSize = 10;
				CT_RPr rpr = run.GetCTR().AddNewRPr();
				rpr.vertAlign = new CT_VerticalAlignRun();
				rpr.vertAlign.val = type == "sup" ? ST_VerticalAlignRun.superscript : ST_VerticalAlignRun.subscript;
				run.SetText(tmp);

				text = text.Substring(indexEnd + 6);
			}
			while (ContainSubSup(text));

			run = paragraph.CreateRun();
			run.SetText(text);
			run.FontSize = 10;

			return run;
		}

		/// <summary>
		/// 摘要导出成excel 的上下标改变
		/// </summary>
		/// <param name="workbook"></param>
		/// <param name="text"></param>
		/// <returns></returns>
		public static XSSFRichTextString ChangeSubSupForExcel(XSSFWorkbook workbook, string text)
		{
			text = text.Replace(strHtmlSupStart, SupSubNeedChange.宏银需要改变的上标开始);
			text = text.Replace(strHtmlSupEnd, SupSubNeedChange.宏银需要改变的上标结束);
			text = text.Replace(strHtmlSubStart, SupSubNeedChange.宏银需要改变的下标开始);
			text = text.Replace(strHtmlSubEnd, SupSubNeedChange.宏银需要改变的下标结束);

			text = GetNoHtml(text);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标开始, strHtmlSupStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标结束, strHtmlSupEnd);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标开始, strHtmlSubStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标结束, strHtmlSubEnd);

			List<int> supCountList = new List<int>(); //上标位置list
			List<int> subCountList = new List<int>(); //下标位置list
			do
			{
				var indexStart = text.IndexOf(strHtmlSupStart);
				var indexStart2 = text.IndexOf(strHtmlSubStart); ;

				if (indexStart != -1 && indexStart2 != -1)
				{
					if (indexStart < indexStart2)
					{
						supCountList.Add(indexStart);
						text = text.Remove(indexStart, 5);
						var endIndex = text.IndexOf(strHtmlSupEnd);
						supCountList.Add(endIndex);
						text = text.Remove(endIndex, 6);
					}
					else
					{
						subCountList.Add(indexStart2);
						text = text.Remove(indexStart2, 5);
						var endIndex = text.IndexOf(strHtmlSubEnd);
						subCountList.Add(endIndex);
						text = text.Remove(endIndex, 6);
					}
				}
				else
				{
					if (indexStart != -1)
					{
						supCountList.Add(indexStart);
						text = text.Remove(indexStart, 5);
						var endIndex = text.IndexOf(strHtmlSupEnd);
						supCountList.Add(endIndex);
						text = text.Remove(endIndex, 6);
					}
					else if (indexStart2 != -1)
					{
						subCountList.Add(indexStart2);
						text = text.Remove(indexStart2, 5);
						var endIndex = text.IndexOf(strHtmlSubEnd);
						subCountList.Add(endIndex);
						text = text.Remove(endIndex, 6);
					}
				}
			}
			while (ContainSubSup(text));

			XSSFRichTextString returnExcelText = new XSSFRichTextString(text);

			IFont ft3 = workbook.CreateFont();
			ft3.FontName = "宋体";
			returnExcelText.ApplyFont(0, text.Length, ft3);

			IFont ft = workbook.CreateFont();
			ft.TypeOffset = FontSuperScript.Super;
			for (var index = 0; index < supCountList.Count() / 2; index++)
			{
				returnExcelText.ApplyFont(supCountList[2 * index], supCountList[2 * index + 1], ft);
			}

			IFont ft2 = workbook.CreateFont();
			ft2.TypeOffset = FontSuperScript.Sub;
			for (var index = 0; index < subCountList.Count() / 2; index++)
			{
				returnExcelText.ApplyFont(subCountList[2 * index], subCountList[2 * index + 1], ft2);
			}

			return returnExcelText;
		}

		/// <summary>
		/// 移动端-清除上下标
		/// </summary>
		/// <param name="text"></param>
		/// <returns></returns>
		public static string GetNoHtmlLeaveSubSup(string text)
		{
			text = text.Replace(strHtmlSupStart, SupSubNeedChange.宏银需要改变的上标开始);
			text = text.Replace(strHtmlSupEnd, SupSubNeedChange.宏银需要改变的上标结束);
			text = text.Replace(strHtmlSubStart, SupSubNeedChange.宏银需要改变的下标开始);
			text = text.Replace(strHtmlSubEnd, SupSubNeedChange.宏银需要改变的下标结束);

			text = GetNoHtml(text);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标开始, strHtmlSupStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的上标结束, strHtmlSupEnd);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标开始, strHtmlSubStart);
			text = text.Replace(SupSubNeedChange.宏银需要改变的下标结束, strHtmlSubEnd);
			return text;
		}

		/// <summary>
		/// 生成PDF
		/// </summary>
		/// <param name="international"></param>
		/// <param name="conferenceNotice"></param>
		/// <param name="stampFile"></param>
		/// <param name="pdfFile"></param>
		/// <param name="userName"></param>
		/// <param name="contribute"></param>
		public static void CreatePdf(ConferenceMaster conferenceMaster, ConferenceNoticeMaster conferenceNotice,
				string stampFile, string pdfFile, string userName,
				ConferenceContributeInfo contribute = null)
		{
			var emptyStr = "     ";
			var dbContext = new CISEntities();

			//参会费
			var attendFees = dbContext.FeeAttendenceMaster.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceNotice.ID &&
						x.Status == Status.正常).OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).ToList();

			//文章出版费
			var pageFees = dbContext.FeePageMaster.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceNotice.ID &&
						x.Status == Status.正常).OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).ToList();

			//餐费
			var mealFees = dbContext.FeeMealMaster.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceNotice.ID &&
						x.Status == Status.正常).OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).ToList();

			//其他费用
			var otherFees = dbContext.FeeOtherMaster.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceNotice.ID &&
						x.Status == Status.正常).OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).ToList();

			//会议网址
			var meetingUrl = conferenceNotice.HomePageUrl;
			if (string.IsNullOrEmpty(meetingUrl))
			{
				meetingUrl = SystemWeb + "/MeetingMain/Index/" +
						conferenceNotice.ConferenceNickName;
			}

			List<string> authorName = new List<string>();
			string reportType = string.Empty;
			if (contribute != null)
			{
				//所有作者姓名
				authorName = dbContext.AuthorInfo.AsNoTracking()
						.Where(x => x.ContributeId == contribute.ID)
						.OrderBy(x => x.Sort)
						.ThenByDescending(x => x.CreateDate)
						.Select(x => x.FullName).ToList();

				//报告类型
				if (!string.IsNullOrEmpty(contribute.ReportId))
				{
					reportType = (dbContext.ReportMaster.AsNoTracking()
									.FirstOrDefault(x => x.ID == contribute.ReportId))
									?.ReportType;
				}
			}

			iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4);
			PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfFile, FileMode.Create));

			//定义一个Document，并设置页面大小为A4，竖向
			doc.AddAuthor(userName);
			doc.AddCreationDate();
			doc.AddCreator(userName);
			doc.AddSubject("ConferenceNotice");
			doc.AddTitle("ConferenceNotice");
			doc.AddKeywords("ASP.NET,PDF,iTextSharp,ConferenceNotice");
			//自定义头 
			doc.AddHeader("Expires", "0");
			doc.Open();
			//插入conferenceName
			BaseFont bfSun = BaseFont.CreateFont("C:\\Windows\\Fonts\\msyh.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//微软雅黑
			Font sun16red = new Font(bfSun, 16, Font.BOLD, BaseColor.BLACK);//微软雅黑16号 黑色 加粗

			#region PDF文件
			if (conferenceMaster.IsInternational)
			{
				//国际会议
				//Conference Name
				Paragraph conferenceName = new Paragraph(conferenceNotice.ConferenceName, sun16red);
				conferenceName.Alignment = Rectangle.ALIGN_CENTER;
				doc.Add(conferenceName);

				//Invitation Letter
				Paragraph title = new Paragraph("Invitation Letter", sun16red);
				title.Alignment = Rectangle.ALIGN_CENTER;
				doc.Add(title);

				//Dear  [所有作者的名字, Authors]  ,
				string authors = authorName.Count > 0 ? string.Join(strSemicolon, authorName) : emptyStr;
				Font fontNormal = new Font(bfSun, 10, Font.NORMAL);
				Font fontUnderline = new Font(bfSun, 10, Font.UNDERLINE);
				Phrase authorPhrase1 = new Phrase("Dear Mr. /Ms. ", fontNormal);
				Phrase authorPhrase2 = new Phrase(authors, fontUnderline);
				Paragraph authorParagraph = new Paragraph();
				authorParagraph.Add(authorPhrase1);
				authorParagraph.Add(authorPhrase2);
				authorParagraph.SpacingBefore = 5;
				doc.Add(authorParagraph);

				//[Conference Name] will be held on [Conference Date], in [Conference Location]. [Conference NickName] is hosted by [Host1], [Host2], [Host3].
				var sponsors = string.IsNullOrEmpty(conferenceNotice.Sponsor) ? string.Empty.Split(chrSemicolon) : conferenceNotice.Sponsor.Replace("；", ";").Replace("#", Stamp.StampEN).Split(chrSemicolon);
				var host = string.Empty;
				if (sponsors.Length > 0)
				{
					for (var index = 0; index < sponsors.Length; index++)
					{
						host += sponsors[index];
						host += index != sponsors.Length - 1 ? ", " : ".";
					}
				}
				var strConferenceInfo = conferenceNotice.ConferenceName + " will be held on " + conferenceNotice.OperateTime + ", in " + conferenceNotice.OperateLocation + ". " +
						conferenceNotice.ConferenceNickName + " is hosted by " + host;
				Paragraph conferenceInfo = new Paragraph(strConferenceInfo, fontNormal);
				conferenceInfo.FirstLineIndent = 20;
				conferenceInfo.SpacingBefore = 5;
				doc.Add(conferenceInfo);

				//Your paper ID [Contribution ID] entitled as [Title] submitted to [Conference NickName] has been accepted as the [Report Type]  presentation. 
				//We are honored to invite you to attend the conference and give the presentation according to the program.
				Chunk noticeChunk1 = new Chunk("Your paper ID ", fontNormal);
				Chunk noticeChunk2 = new Chunk(contribute != null ? contribute.ID : emptyStr, fontUnderline);
				Chunk noticeChunk3 = new Chunk(" entitled as ", fontNormal);
				Chunk noticeChunk4 = new Chunk(contribute != null ? contribute.EssayTitle : emptyStr, fontUnderline);
				Chunk noticeChunk5 = new Chunk(" submitted to ", fontNormal);
				Chunk noticeChunk6 = new Chunk(conferenceNotice.ConferenceNickName, fontUnderline);
				Chunk noticeChunk7 = new Chunk(" has been accepted as the ", fontNormal);
				Chunk noticeChunk8 = new Chunk(!string.IsNullOrEmpty(reportType) ? reportType : emptyStr, fontUnderline);
				Chunk noticeChunk9 = new Chunk(" presentation. We are honored to invite you to attend the conference and give the presentation according to the program.", fontNormal);

				Phrase noticePhrase1 = new Phrase();
				noticePhrase1.Add(noticeChunk1);
				noticePhrase1.Add(noticeChunk2);
				noticePhrase1.Add(noticeChunk3);
				noticePhrase1.Add(noticeChunk4);
				noticePhrase1.Add(noticeChunk5);
				noticePhrase1.Add(noticeChunk6);
				noticePhrase1.Add(noticeChunk7);
				noticePhrase1.Add(noticeChunk8);
				noticePhrase1.Add(noticeChunk9);

				Font bold = new Font(bfSun, 10, Font.BOLD);

				Paragraph noticeParagraph = new Paragraph();
				noticeParagraph.Add(noticePhrase1);
				noticeParagraph.FirstLineIndent = 20;
				doc.Add(noticeParagraph);

				if (!string.IsNullOrEmpty(conferenceNotice.CustomDefinition))
				{
					byte[] data = Encoding.UTF8.GetBytes(conferenceNotice.CustomDefinition);
					MemoryStream msInput = new MemoryStream(data);
					XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
				}

				if (attendFees.Count + pageFees.Count + mealFees.Count + otherFees.Count > 0)
				{
					//Registration Fee:
					Paragraph feeParagraph = new Paragraph("Registration Fee: ", bold);
					feeParagraph.FirstLineIndent = 20;
					feeParagraph.SpacingBefore = 5;
					doc.Add(feeParagraph);

					//table		
					PdfPTable table = new PdfPTable(3);

					if (attendFees.Count > 0)
					{
						table.AddCell(new Phrase("Registration Fee", bold));
						table.AddCell(new Phrase("Discount Price", bold));
						table.AddCell(new Phrase("Normal Price", bold));
						foreach (var attendFee in attendFees)
						{
							table.AddCell(new Phrase(attendFee.RegisterType, fontNormal));
							table.AddCell(new Phrase(attendFee.Currency + attendFee.Discount.Value.ToString("N2"), fontNormal));
							table.AddCell(new Phrase(attendFee.Currency + attendFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (pageFees.Count > 0)
					{
						table.AddCell(new Phrase("Publication Fee", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("Normal Price", bold));
						foreach (var pageFee in pageFees)
						{
							table.AddCell(new Phrase(pageFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(pageFee.Currency + pageFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (mealFees.Count > 0)
					{
						table.AddCell(new Phrase("Meal Fee", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("Normal Price", bold));
						foreach (var mealFee in mealFees)
						{
							table.AddCell(new Phrase(mealFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(mealFee.Currency + mealFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (otherFees.Count > 0)
					{
						table.AddCell(new Phrase("Other Fees", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("Normal Price", bold));
						foreach (var otherFee in otherFees)
						{
							table.AddCell(new Phrase(otherFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(otherFee.Currency + otherFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					table.SpacingAfter = 10;
					table.SpacingBefore = 10;

					doc.Add(table);

					//Note: The meals and accommodation fees are not included in the registration fee.”
					//Phrase mealNoticePhrase1 = new Phrase("Note: ", bold);
					//Phrase mealNoticePhrase2 = new Phrase("The meals and accommodation fees are not included in the registration fee.", fontNormal);
					//Paragraph mealNoticeParagraph = new Paragraph();
					//mealNoticeParagraph.Add(mealNoticePhrase1);
					//mealNoticeParagraph.Add(mealNoticePhrase2);
					//doc.Add(mealNoticeParagraph);

					if (conferenceMaster.BenefitEndDate.HasValue)
					{
						//Early Bird Registration Deadline: [Benefit End Date] (online registration and payment required)
						Font sun12red = new Font(bfSun, 10, Font.NORMAL, BaseColor.RED);//宋体10号 红色 
						Font sun12redbold = new Font(bfSun, 10, Font.BOLD, BaseColor.RED);//宋体10号 红色 粗体

						var benefitEndDate = conferenceMaster.BenefitEndDate.Value.ToString("MM/dd/yyyy");
						Phrase benefitNoticePhrase1 = new Phrase("Early Bird Registration Deadline: ", bold);
						Phrase benefitNoticePhrase2 = new Phrase(benefitEndDate, fontNormal);
						Phrase benefitNoticePhrase3 = new Phrase(" (online registration and payment required)", fontNormal);
						Paragraph benefitNoticeParagraph = new Paragraph();
						benefitNoticeParagraph.Add(benefitNoticePhrase1);
						benefitNoticeParagraph.Add(benefitNoticePhrase2);
						benefitNoticeParagraph.Add(benefitNoticePhrase3);
						doc.Add(benefitNoticeParagraph);
					}
				}

				//[会务支持单位] is the authorized company and in charge of all financial affairs of [Conference NickName].
				Phrase supportPhrase1 = new Phrase(conferenceNotice.Supporter, fontNormal);
				Phrase supportPhrase2 = new Phrase(" is the cooperated company and in charge of all financial affairs of ", fontNormal);
				Phrase supportPhrase3 = new Phrase(conferenceNotice.ConferenceNickName, fontNormal);
				Paragraph supportParagraph = new Paragraph();
				supportParagraph.Add(supportPhrase1);
				supportParagraph.Add(supportPhrase2);
				supportParagraph.Add(supportPhrase3);
				doc.Add(supportParagraph);

				//Venue: [会议地址]
				Phrase locationPhrase1 = new Phrase("Venue: ", bold);
				Phrase locationPhrase2 = new Phrase(conferenceNotice.ConferenceAddress, fontNormal);
				Paragraph locationParagraph = new Paragraph();
				locationParagraph.Add(locationPhrase1);
				locationParagraph.Add(locationPhrase2);
				doc.Add(locationParagraph);

				//Contact Us: 
				var contacts = conferenceNotice.Contact.Replace("；", ";").Split(chrSemicolon);
				var contactPhones = conferenceNotice.ContactPhone.Replace("；", ";").Split(chrSemicolon);
				var contactMail = conferenceNotice.ContactMail.Replace("；", ";").Split(chrSemicolon);

				Phrase contactPhrase1 = new Phrase("Contact Us: ", bold);
				Phrase contactPhrase2 = new Phrase(contacts[0] + strSemicolon + strSpace + contactPhones[0] +
						strSemicolon + strSpace + contactMail[0], fontNormal);
				Paragraph contactParagraph = new Paragraph();
				contactParagraph.Add(contactPhrase1);
				contactParagraph.Add(contactPhrase2);
				doc.Add(contactParagraph);

				if (contacts.Length > 1)
				{
					for (var index = 1; index < contacts.Length; index++)
					{
						var contactBody = contacts[index] + strSemicolon + strSpace + contactPhones[index] +
								strSemicolon + strSpace + contactMail[index];
						Phrase contactPhraseIndex = new Phrase(contactBody, fontNormal);
						Paragraph contactIndexParagraph = new Paragraph();
						contactIndexParagraph.Add(contactPhraseIndex);
						contactIndexParagraph.IndentationLeft = 57.5f;
						doc.Add(contactIndexParagraph);
					}
				}

				//Conference Website: [ Conference Home Page]
				Phrase domainPhrase1 = new Phrase("Conference Website: ", bold);
				Phrase domainPhrase2 = new Phrase(meetingUrl, fontNormal);
				Paragraph domainParagraph = new Paragraph();
				domainParagraph.Add(domainPhrase1);
				domainParagraph.Add(domainPhrase2);
				doc.Add(domainParagraph);

				//署名
				Paragraph sponsorParagraph = new Paragraph("\r\n\r\n\r\n", fontNormal);
				sponsorParagraph.Alignment = Element.ALIGN_RIGHT;
				if (sponsors.Length > 0)
				{
					for (var index = 0; index < sponsors.Length; index++)
					{
						Phrase sponsorPhrase = new Phrase(sponsors[index] + "\r\n", fontNormal);
						sponsorParagraph.Add(sponsorPhrase);
					}
				}

				//当前时间
				var today = DateTime.Now.ToString("MM/dd/yyyy");
				Phrase timePhrase = new Phrase(today, fontNormal);
				sponsorParagraph.Add(timePhrase);
				doc.Add(sponsorParagraph);
			}
			else
			{
				//国内会议
				//插入会议名称
				if (conferenceNotice.ConferenceName.Length > 32 && conferenceNotice.ConferenceName.IndexOf("暨") > 0)
				{
					var index = conferenceNotice.ConferenceName.IndexOf("暨");
					var tmp1 = conferenceNotice.ConferenceName.Substring(0, index);
					var tmp2 = conferenceNotice.ConferenceName.Substring(index);

					Paragraph conferenceName = new Paragraph(tmp1, sun16red);
					conferenceName.Alignment = Rectangle.ALIGN_CENTER;
					doc.Add(conferenceName);
					conferenceName = new Paragraph(tmp2, sun16red);
					conferenceName.Alignment = Rectangle.ALIGN_CENTER;
					doc.Add(conferenceName);
				}
				else
				{
					Paragraph conferenceName = new Paragraph(conferenceNotice.ConferenceName, sun16red);
					conferenceName.Alignment = Rectangle.ALIGN_CENTER;
					doc.Add(conferenceName);
				}

				//插入title ： 会议通知
				Paragraph title = new Paragraph("会议通知", sun16red);
				title.Alignment = Rectangle.ALIGN_CENTER;
				doc.Add(title);

				//插入作者行
				string authors = authorName.Count > 0 ? string.Join(strSemicolon, authorName) : emptyStr;
				Font fontNormal = new Font(bfSun, 10, Font.NORMAL);
				Font fontUnderline = new Font(bfSun, 10, Font.UNDERLINE);
				Font fontBOLD = new Font(bfSun, 10, Font.BOLD);
				Font fontITALIC = new Font(bfSun, 10, Font.ITALIC);
				Phrase authorPhrase1 = new Phrase("尊敬的 ", fontNormal);
				Phrase authorPhrase2 = new Phrase(authors, fontUnderline);
				Phrase authorPhrase3 = new Phrase(" 作者：", fontNormal);
				Paragraph authorParagraph = new Paragraph();
				authorParagraph.Add(authorPhrase1);
				authorParagraph.Add(authorPhrase2);
				authorParagraph.Add(authorPhrase3);
				authorParagraph.SpacingBefore = 5;
				doc.Add(authorParagraph);

				//会议信息 【主办单位】将于【举办时间】在【举办地点】举办【会议名称】。
				var sponsor = string.IsNullOrEmpty(conferenceNotice.Sponsor) ? string.Empty : conferenceNotice.Sponsor.Replace("；", ";").Replace("#", "");
				var sponsorList = sponsor.Split(';');
				var sponsorString = string.Join("，", sponsorList);
				var strConferenceInfo = sponsorString + "将于" + conferenceNotice.OperateTime + "在" + conferenceNotice.OperateLocation + "举办" + conferenceNotice.ConferenceName + "。";
				Paragraph conferenceInfo = new Paragraph(strConferenceInfo, fontNormal);
				conferenceInfo.FirstLineIndent = 20;
				conferenceInfo.SpacingBefore = 5;
				doc.Add(conferenceInfo);

				//投稿notice
				var strNotice = "您投递到该会议的题为“" + (contribute != null ? contribute.EssayTitle : emptyStr) + "”的论文被大会接受为" + (!string.IsNullOrEmpty(reportType) ? reportType : emptyStr) + "，";
				strNotice += "编号为" + (contribute != null ? contribute.ID : emptyStr) + "，欢迎您按时来参加会议。";
				Chunk noticeChunk1 = new Chunk("您投递到该会议的题为“", fontNormal);
				Chunk noticeChunk2 = new Chunk(contribute != null ? contribute.EssayTitle : emptyStr, fontUnderline);
				Chunk noticeChunk3 = new Chunk("”的论文被大会接受为", fontNormal);
				Chunk noticeChunk4 = new Chunk(!string.IsNullOrEmpty(reportType) ? reportType : emptyStr, fontUnderline);
				Chunk noticeChunk5 = new Chunk("，编号为", fontNormal);
				Chunk noticeChunk8 = new Chunk(contribute != null ? contribute.ID : emptyStr, fontUnderline);
				Chunk noticeChunk9 = new Chunk("，欢迎您按时来参加会议。", fontNormal);

				Phrase noticePhrase1 = new Phrase();
				noticePhrase1.Add(noticeChunk1);
				noticePhrase1.Add(noticeChunk2);
				noticePhrase1.Add(noticeChunk3);
				noticePhrase1.Add(noticeChunk4);
				noticePhrase1.Add(noticeChunk5);
				noticePhrase1.Add(noticeChunk8);
				noticePhrase1.Add(noticeChunk9);

				Font bold = new Font(bfSun, 10, Font.BOLD);

				Paragraph noticeParagraph = new Paragraph();
				noticeParagraph.Add(noticePhrase1);
				noticeParagraph.FirstLineIndent = 20;
				doc.Add(noticeParagraph);

				if (!string.IsNullOrEmpty(conferenceNotice.CustomDefinition))
				{
					byte[] data = Encoding.UTF8.GetBytes(conferenceNotice.CustomDefinition);
					MemoryStream msInput = new MemoryStream(data);
					XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
				}

				if (attendFees.Count + pageFees.Count + mealFees.Count + otherFees.Count > 0)
				{
					//会议费用title
					Paragraph feeParagraph = new Paragraph("会议费用如下：", fontNormal);
					feeParagraph.FirstLineIndent = 20;
					feeParagraph.SpacingBefore = 5;
					doc.Add(feeParagraph);

					//table		
					PdfPTable table = new PdfPTable(3);

					if (attendFees.Count > 0)
					{
						table.AddCell(new Phrase("参会费", bold));
						table.AddCell(new Phrase("优惠价格", bold));
						table.AddCell(new Phrase("正常价格", bold));
						foreach (var attendFee in attendFees)
						{
							table.AddCell(new Phrase(attendFee.RegisterType, fontNormal));
							table.AddCell(new Phrase(attendFee.Currency + attendFee.Discount.Value.ToString("N2"), fontNormal));
							table.AddCell(new Phrase(attendFee.Currency + attendFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (pageFees.Count > 0)
					{
						table.AddCell(new Phrase("文章出版费", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("正常价格", bold));
						foreach (var pageFee in pageFees)
						{
							table.AddCell(new Phrase(pageFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(pageFee.Currency + pageFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (mealFees.Count > 0)
					{
						table.AddCell(new Phrase("餐费", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("正常价格", bold));
						foreach (var mealFee in mealFees)
						{
							table.AddCell(new Phrase(mealFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(mealFee.Currency + mealFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					if (otherFees.Count > 0)
					{
						table.AddCell(new Phrase("其他费用", bold));
						table.AddCell(new Phrase(string.Empty, fontNormal));
						table.AddCell(new Phrase("正常价格", bold));
						foreach (var otherFee in otherFees)
						{
							table.AddCell(new Phrase(otherFee.FeeName, fontNormal));
							table.AddCell(string.Empty);
							table.AddCell(new Phrase(otherFee.Currency + otherFee.Price.Value.ToString("N2"), fontNormal));
						}
					}

					table.SpacingAfter = 10;
					table.SpacingBefore = 10;

					doc.Add(table);

					//注：在【优惠结束时间】之前交费，享受优惠期价格。
					if (conferenceMaster.BenefitEndDate.HasValue)
					{
						Font sun12red = new Font(bfSun, 10, Font.NORMAL, BaseColor.RED);//宋体10号 红色 
						Font sun12redbold = new Font(bfSun, 10, Font.BOLD, BaseColor.RED);//宋体10号 红色 粗体

						var benefitEndDate = conferenceMaster.BenefitEndDate.Value.ToString("yyyy-MM-dd");
						Phrase benefitNoticePhrase1 = new Phrase("注：在 ", sun12red);
						Phrase benefitNoticePhrase2 = new Phrase(benefitEndDate, sun12redbold);
						Phrase benefitNoticePhrase3 = new Phrase(" 之前交费，享受优惠期价格。", sun12red);
						Paragraph benefitNoticeParagraph = new Paragraph();
						benefitNoticeParagraph.Add(benefitNoticePhrase1);
						benefitNoticeParagraph.Add(benefitNoticePhrase2);
						benefitNoticeParagraph.Add(benefitNoticePhrase3);
						doc.Add(benefitNoticeParagraph);
					}

					//本次会议食宿自理，无伙食补贴。
					Paragraph mealNoticeParagraph = new Paragraph("本次会议食宿自理，无伙食补贴。", bold);
					mealNoticeParagraph.FirstLineIndent = 20;
					doc.Add(mealNoticeParagraph);
				}

				//会议地点
				Phrase locationPhrase1 = new Phrase("会议地点：", bold);
				Phrase locationPhrase2 = new Phrase(conferenceNotice.ConferenceAddress, fontNormal);
				Paragraph locationParagraph = new Paragraph();
				locationParagraph.Add(locationPhrase1);
				locationParagraph.Add(locationPhrase2);
				doc.Add(locationParagraph);

				//会务支持单位
				Phrase supportPhrase1 = new Phrase("会务支持单位：", bold);
				Phrase supportPhrase2 = new Phrase(conferenceNotice.Supporter, fontNormal);
				Paragraph supportParagraph = new Paragraph();
				supportParagraph.Add(supportPhrase1);
				supportParagraph.Add(supportPhrase2);
				doc.Add(supportParagraph);

				//会务联系人
				var contacts = conferenceNotice.Contact.Replace("；", ";").Split(chrSemicolon);
				var contactPhones = conferenceNotice.ContactPhone.Replace("；", ";").Split(chrSemicolon);
				var contactMail = conferenceNotice.ContactMail.Replace("；", ";").Split(chrSemicolon);

				Phrase contactPhrase1 = new Phrase("会务联系人：", bold);
				Phrase contactPhrase2 = new Phrase(contacts[0] + strSemicolon + strSpace + contactPhones[0] +
						strSemicolon + strSpace + contactMail[0], fontNormal);
				Paragraph contactParagraph = new Paragraph();
				contactParagraph.Add(contactPhrase1);
				contactParagraph.Add(contactPhrase2);
				doc.Add(contactParagraph);

				if (contacts.Length > 1)
				{
					for (var index = 1; index < contacts.Length; index++)
					{
						var contactBody = contacts[index] + strSemicolon + strSpace + contactPhones[index] +
								strSemicolon + strSpace + contactMail[index];
						Phrase contactPhraseIndex = new Phrase(contactBody, fontNormal);
						Paragraph contactIndexParagraph = new Paragraph();
						contactIndexParagraph.Add(contactPhraseIndex);
						contactIndexParagraph.IndentationLeft = 60;
						doc.Add(contactIndexParagraph);
					}
				}

				//会议网址
				Phrase domainPhrase1 = new Phrase("会议网址：", bold);
				Phrase domainPhrase2 = new Phrase(meetingUrl, fontNormal);
				Paragraph domainParagraph = new Paragraph();
				domainParagraph.Add(domainPhrase1);
				domainParagraph.Add(domainPhrase2);
				doc.Add(domainParagraph);

				//署名
				Paragraph sponsorParagraph = new Paragraph("\r\n\r\n\r\n", fontNormal);
				sponsorParagraph.Alignment = Element.ALIGN_RIGHT;
				var sponsors = string.IsNullOrEmpty(conferenceNotice.Sponsor) ? string.Empty.Split(chrSemicolon) : conferenceNotice.Sponsor.Replace("；", ";").Replace("#", Stamp.StampCN).Split(chrSemicolon);
				if (sponsors.Length > 0)
				{
					for (var index = 0; index < sponsors.Length; index++)
					{
						Phrase sponsorPhrase = new Phrase(sponsors[index] + "\r\n", fontNormal);
						sponsorParagraph.Add(sponsorPhrase);
					}
				}

				//当前时间
				var today = DateTime.Now.ToString("yyyy年MM月dd日");
				Phrase timePhrase = new Phrase(today, fontNormal);
				sponsorParagraph.Add(timePhrase);
				doc.Add(sponsorParagraph);
			}

			if (!string.IsNullOrEmpty(stampFile))
			{
				//图章
				Paragraph stampParagraph = new Paragraph();
				//插入图章 Img
				iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(stampFile);
				//var rate = float.Parse(Math.Round(128 / img.Height, 2).ToString());
				//img.ScaleAbsoluteWidth(img.Width * rate);
				img.ScaleAbsoluteHeight(128);
				img.ScaleAbsoluteWidth(128);
				img.Alignment = Element.ALIGN_RIGHT;

				stampParagraph.Add(img);
				stampParagraph.SpacingBefore = -110;
				doc.Add(stampParagraph);
			}

			doc.Close();
			#endregion
		}

		/// <summary>
		/// 读取导入字段
		/// </summary>
		/// <param name="cell"></param>
		/// <returns></returns>
		public static string ReadExcelField(NPOI.SS.UserModel.ICell cell)
		{
			if (cell.CellType == CellType.Numeric)
			{
				return cell?.NumericCellValue.ToString();
			}

			return cell?.StringCellValue;
		}
		#endregion

		public static string GetRealIP()
		{
			string result = string.Empty;
			result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
			//可能有代理   
			if (!string.IsNullOrWhiteSpace(result))
			{
				//没有"." 肯定是非IP格式  
				if (result.IndexOf(".") == -1)
				{
					result = null;
				}
				else
				{
					//有","，估计多个代理。取第一个不是内网的IP。  
					if (result.IndexOf(",") != -1)
					{
						result = result.Replace(" ", string.Empty).Replace("\"", string.Empty);

						string[] temparyip = result.Split(",;".ToCharArray());

						if (temparyip != null && temparyip.Length > 0)
						{
							for (int i = 0; i < temparyip.Length; i++)
							{
								//找到不是内网的地址  
								if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
								{
									return temparyip[i];
								}
							}
						}
					}
					//代理即是IP格式  
					else if (IsIPAddress(result))
					{
						return result;
					}
					//代理中的内容非IP  
					else
					{
						result = null;
					}
				}
			}

			if (string.IsNullOrWhiteSpace(result))
			{
				result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
			}

			if (string.IsNullOrWhiteSpace(result))
			{
				result = HttpContext.Current.Request.UserHostAddress;
			}
			return result;
		}

		private static bool IsIPAddress(string str)
		{
			if (string.IsNullOrWhiteSpace(str) || str.Length < 7 || str.Length > 15)
				return false;

			string regformat = @"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})";
			Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);

			return regex.IsMatch(str);
		}
	}

	public class UnicodeFontFactory : FontFactoryImp
	{
		private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msyh.ttc,0");

		private readonly BaseFont _baseFont;

		public UnicodeFontFactory()
		{
			_baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		}

		public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
		{
			return new Font(_baseFont, size, style, color);
		}
	}
}